package br.com.smartrunner.business.persistence.control;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.com.smartrunner.business.exceptions.AppException;

public class PersistenceControl {

	private String							url = "jdbc:mysql://localhost:3306/smartrunner";
	private String							user = "root";
	private String							password = "jean";
	private String							driverClassName = "com.mysql.jdbc.Driver";
	private Connection						connection = null;
	private List<PreparedStatement>			preparedStatement = null;
	
	protected PersistenceControl() {
		try {
			Class.forName(this.driverClassName);
			this.connection = DriverManager.getConnection(this.url, this.user, this.password);
			this.preparedStatement = new ArrayList<PreparedStatement>();
		} catch (Exception e) {
			throw new AppException(e);
		}
	}
	
	protected PreparedStatement prepareStatement(String sql) {
		try {
			PreparedStatement ps = this.connection.prepareStatement(sql);
			this.preparedStatement.add(ps); 
			return ps;
		} catch (SQLException e) {
			throw new AppException(e);
		}
	}
	
	protected void close() {
		try {
			for (PreparedStatement ps : this.preparedStatement) {
				ps.close();
			}
			this.connection.close();
		} catch (SQLException e) {
			throw new AppException(e);
		}
	}
}
